#include "thread.h"
#include "thread_binder.h"
#include <windows.h>
void* CThread::Wrapper(void* arg)
{
    CThread* _this = (CThread*)arg;
    _this->Execute();
    CThreadBinder::ExitFromThread(_this->m_ret_val);
    if (_this->m_listener != 0)
    {
        _this->m_listener->NotifyOnFinished();
    }
    return (void*)(_this->m_ret_val);
}

CThread::CThread(CThreadListener *listener)
{
    m_thread_id = 0;
    m_ret_val = 0;
    m_listener = listener;
}

CThread::~CThread()
{
    if (!m_make_success)
    {
        return;
    }
    WaitFor();
    CThreadBinder::CleanThread(m_thread_id);
    if (m_listener != 0)
    {
        delete m_listener;
    }
}

void CThread::Run()
{
    long err = CThreadBinder::MakeThread(&m_thread_id, Wrapper, this);
    if (err)
    {
        m_make_success = false;
    }
    else
    {
        m_make_success = true;
    }
}

void CThread::WaitFor()
{
    CThreadBinder::WaitFor(m_thread_id);
}

unsigned long CThread::GetThreadId()
{
    return m_thread_id;
}

int CThread::GetResult()
{
    return m_ret_val;
}
